﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YouDaoNotesCodes
{
    class selfDefine2Section : ConfigurationSection
    {
        #region 自定义配置文件读取-方式2：Element
        [ConfigurationProperty("Users", IsRequired = true)]
        public SectionElement Users
        {
            get { return (SectionElement)this["Users"]; }
        }
        public class SectionElement : ConfigurationElement
        {
            [ConfigurationProperty("UserName", IsRequired = true)]
            public string UserName
            {
                get { return this["UserName"].ToString(); }
                set { this["UserName"] = value; }
            }

            [ConfigurationProperty("Password", IsRequired = true)]
            public string Password
            {
                get { return this["Password"].ToString(); }
                set { this["Password"] = value; }
            }
        }
        #endregion

        //方式2调用
        public void getSectionByElement()
        {
            selfDefine2Section se2 = (selfDefine2Section)ConfigurationManager.GetSection("selfDefine2");
            string res = se2.Users.UserName;
            Console.Write(res);
            Console.ReadKey();
        }

        #region 自定义配置文件写入-方式2
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        public void writeSectionByElement()
        {
            selfDefine2Section sectioin2 = config.GetSection("selfDefine2") as selfDefine2Section;
            sectioin2.Users.UserName = "zwq22";
            sectioin2.Users.Password = "qqqqqq";
            config.Save();
        }
        #endregion
    }
}
